package com.ccreservoirs.config;

import java.time.Duration;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisConfig {
	
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
				.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMillis(1000 * 30)))
				.build();
		return cacheManager;
	}
	
	//
	// @Bean
	// public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory
	// factory) {
	// StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
	// stringRedisTemplate.setConnectionFactory(factory);
	// return stringRedisTemplate;
	// }
	
	@Bean
	RedisMessageListenerContainer keyExpirationListenerContainer(RedisConnectionFactory connectionFactory) {

		RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
		listenerContainer.setConnectionFactory(connectionFactory);

		listenerContainer.addMessageListener((message, pattern) -> {

			System.out.println(message + "  " + new String(pattern));

		}, new PatternTopic("__keyevent@6__:expired"));

		return listenerContainer;
	}


}
